<?php
namespace app\admin\controller;
use app\model\Category as CategoryModel;
use think\Db;


class Category extends Base
{
    public function __construct(){
        $model = new CategoryModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        if ( in_array($page_info['action'], ['add','edit']) ) {
            $pids = $this->getCategoryRecursion(0,0,$pid_map);
            $fields = [
                'pid'=>['name'=>'上级分类','type'=>'select1_1','params'=>$pids],
                'name'=>['name'=>'名称','type'=>'text'],
                'type'=>['name'=>'显示方式','type'=>'select1','params'=>$model->getTypeList()],
                'attribute'=>['name'=>'属性','type'=>'checkbox','params'=>$model->getAttributeList()],
                'view_url'=>['name'=>'页面模板','type'=>'text','placeholder'=>'空为默认'],
                'sort'=>['name'=>'排序值','type'=>'text'],
                'status'=>['name'=>'状态','type'=>'select1','params'=>$model->getStatusList()],
                'cover'=>['name'=>'图标','type'=>'file'],
                'description'=>['name'=>'描述','type'=>'textarea'],
                'content'=>['name'=>'内容','type'=>'ueditor'],
                'redirect_cid'=>['name'=>'跳转其他分类','type'=>'select1_1','params'=>$pids],
                'outside_url'=>['name'=>'外链','type'=>'text'],
            ];
            $valids = createPageValid($fields);
            $this->assign([
                'fields'=>$fields,
                'valids'=>$valids
            ]);
        }

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like']
        ];
        $map = getSearchParam($map_params);
        $map[] = ['pid','=',0];
        $order = 'sort desc,id asc';

        $list['data'] = $model->where($map)->order($order)->select()->toarray();
        $category_ids = array_column($list['data'], 'id');
        $new_obj = [];
        foreach ($list['data'] as $vo) {
            $new_obj[] = $vo;
            $childs = $model->where( 'pid', $vo['id'] )->order($order)->select()->toarray();
            $category_ids = array_merge($category_ids,array_column($childs, 'id'));
            foreach ($childs as $child) {
                $child['name'] = stringRange('&nbsp;',3).'☇'.$child['name'];
                $new_obj[] = $child;
                $childs2 = $model->where( 'pid', $child['id'] )->order($order)->select()->toarray();
                $category_ids = array_merge($category_ids,array_column($childs2, 'id'));
                foreach ($childs2 as $child2) {
                    $child2['name'] = stringRange('&nbsp;',6).'☇'.$child2['name'];
                    $new_obj[] = $child2;
                }
            }
        }
        $list['data'] = $new_obj;

        $map = getSearchParam($map_params);
        $map[] = ['id','not in',$category_ids];
        $list2 = $model->where($map)->select()->toarray();
        foreach ($list2 as $k => $vo) {
            $list2[$k]['error'] = '上级分类异常';
        }
        $list['data'] = array_merge($list['data'],(array)$list2);


        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
            ]
        ];

        return view('index', [
            'list'=>$list,
            'search_params'=>$search_params
        ]);
    }

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['name','type'],
                'nomust'=>['pid','sort','attribute','status','cover','remark','content','view_url','redirect_cid','description','outside_url']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if (!empty($save_data['attribute'])) {
                sort($save_data['attribute']);
                $save_data['attribute'] = implode(',', $save_data['attribute']);
            }
        }
        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        if (request()->isPost()) {
            $fields = [
                'nomust'=>['pid','name','type','sort','attribute','status','cover','remark','content','view_url','redirect_cid','description','outside_url']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if (!empty($save_data['attribute'])) {
                sort($save_data['attribute']);
                $save_data['attribute'] = implode(',', $save_data['attribute']);
            }
        }
        return parent::updateData($id,$save_data);
    }

    // 递归获取
    public static function getCategoryRecursion($id=0,$num=0,$map=[]){
        $model = new CategoryModel();
        $tmp_map = $map;
        $tmp_map[] = ['pid','=',$id];
        $pids = $model->where($tmp_map)->order('sort desc,id asc')->select()->toarray();
        $new_pids = [];
        $childs_num = $num + 1;
        foreach ($pids as $vo) {
            if ($num == 0) {
                $new_pids[$vo['id']] = $vo['name'];
            }else{
                $new_pids[$vo['id']] = stringRange('&nbsp;',$num * 3).'☇'.$vo['name'];
            }
            $childs = \app\admin\controller\Category::getCategoryRecursion($vo['id'],$childs_num,$map);
            if (!empty($childs)) {
                foreach ($childs as $child_k => $child_v) {
                    $new_pids[$child_k] = $child_v;
                }
            }
        }
        return $new_pids;
    }

}
